package com.glela.platform.util;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 日期工具类
 * 
 * @author 
 * 
 */
public class DateUtils {

    private static final Log logger = LogFactory.getLog(DateUtils.class);
    
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.S";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String TIME_FORMAT = "HH:mm:ss";

    public static final String DAYTIME_START = "00:00:00";
    public static final String DAYTIME_END = "23:59:59";

    private static final String[] FORMATS = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd HH:mm:ss", "HH:mm", "HH:mm:ss", "yyyy-MM" ,"yyyy-MM-dd HH:mm:ss.S"};

    /**
     * 相对当前日期，增加或减少天数
     * @param date
     * @param day
     * @return
     */
    public static String addDay(Date date, int day){
        SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
        return df.format(new Date(date.getTime() + day * 24 * 60 * 60 * 1000));
    }

    /**
     * 相对当前日期，增加或减少天数
     * @param date
     * @param day
     * @return
     */
    public static String addDayNew(Date date, Long day){
        SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
        
        return df.format(new Date(date.getTime() + day * 24 * 60 * 60 * 1000));
    }

    public static String convert(Date date) {
        return DateUtils.convert(date, DATE_TIME_FORMAT);
    }

    public static String convert(Date date, String dateFormat) {
        if (date == null) {
			return null;
		}

        if (null == dateFormat) {
			dateFormat = DATE_TIME_FORMAT;
		}

        return new SimpleDateFormat(dateFormat).format(date);
    }

    public static Date convert(String str) {
        if (str != null && str.length() > 0) {
            if (str.length() > 10 && str.charAt(10) == 'T')
			 {
				str = str.replace('T', ' '); // 去掉json-lib加的T字母
			}
            for (String format : FORMATS) {
                if (str.length() == format.length()) {
                    try {
                        Date date = new SimpleDateFormat(format).parse(str);

                        return date;
                    } catch (ParseException e) {
                    	logger.error("时间工具类异常:" ,e);;
                        if (logger.isWarnEnabled()) {
                            logger.warn(e.getMessage());
                        }
                        // logger.warn(e.getMessage());
                    }
                }
            }
        }
        return null;
    }

    public static Date convert(String str, String format) {
        if (!StringUtils.isEmpty(str)) {
            try {
                Date date = new SimpleDateFormat(format).parse(str);
                return date;
            } catch (ParseException e) {
            	logger.error("时间工具类异常:" ,e);;
                if (logger.isWarnEnabled()) {
                    logger.warn(e.getMessage());
                }
                // logger.warn(e.getMessage());
            }
        }
        return null;
    }

    /**
	 * 将传入的Date类型的时�?YYYY-MM-dd)转换成String类型并返�?
	 * @return
	 */
	public static String DateToString(Date date,String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String time = sdf.format(date);
			return time;
		} catch (Exception e) {
			logger.error("时间工具类异常:" ,e);;
		}
		return null;
	}
    
    /**
     * 返回该天到23:59:59结束的日期
     * 
     * @param date
     * @return
     */
    public static Date getEndDatetime(Date date) {
        String thisdate = DateUtils.convert(date, DATE_FORMAT);
        return DateUtils.convert(thisdate + " " + DAYTIME_END);

    }

    /**
     * 返回n天到23:59:59结束的日期
     * 
     * @param date
     * @return
     */
    public static Date getEndDatetime(Date date, Integer diffDays) {
        SimpleDateFormat df=new SimpleDateFormat(DATE_FORMAT);
        String thisdate = df.format(date.getTime() + diffDays * 24 * 60 * 60 * 1000l);
        return DateUtils.convert(thisdate + " " + DAYTIME_END);

    }
    
	/**
	 * 返回该日期加1秒
	 * 
	 * @param date
	 * @return
	 */
    @SuppressWarnings("static-access")
	public static Timestamp getEndTimeAdd(Date endTime){
    	Timestamp ts = new Timestamp(endTime.getTime());
    	Calendar c = Calendar.getInstance();
		c.setTime(ts);
		c.add(Calendar.MILLISECOND, 1000);
		c.set(c.MILLISECOND, 0);
    	return new Timestamp(c.getTimeInMillis());
    }
	/**
	 * 返回该日期的最后一刻，精确到纳秒
	 * 
	 * @param date
	 * @return
	 */
	public static Timestamp getLastEndDatetime(Date endTime) {
		Timestamp ts = new Timestamp(endTime.getTime());
		ts.setNanos(999999999);
		return ts;
	}
    /**
	 * 获取当前时间，返回Date类型
	 * @return
	 */
	public static Date getNowDate(String format){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String temp = DateUtils.getNowString(format);
			return sdf.parse(temp);
		} catch (Exception e) {
			logger.error("时间工具类异常:" ,e);;
		}
		return null;
	}
    
    
    /**
	 * 获取当前时间，返回字符串类型
	 * @return
	 */
	public static String getNowString(String format) {
		try {
			Date now = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String time = sdf.format(now);
			return time;
		} catch (Exception e) {
			logger.error("时间工具类异常:" ,e);;
		}
		return null;
	}
    
    public static String getPidFromDate(Date date) {
		if (date == null) {
			return "";
		}
		
		String m = DateUtils.convert(date, "yyyyMM");
		String d = DateUtils.convert(date, "dd");

		if (Integer.valueOf(d) <= 10) {
			d = "01";
		}
		else if (Integer.valueOf(d) <= 20) {
			d = "02";
		}
		else {
			d = "03";
		}
		
		return m.concat(d);
	}
    
    /**
     * 返回该天从00:00:00开始的日期
     * 
     * @param date
     * @return
     */
    public static Date getStartDatetime(Date date) {
        String thisdate = DateUtils.convert(date, DATE_FORMAT);
        return DateUtils.convert(thisdate + " " + DAYTIME_START);

    }

	/**
     * 返回n天后从00:00:00开始的日期
     * 
     * @param date
     * @return
     */
    public static Date getStartDatetime(Date date, Integer diffDays) {
        SimpleDateFormat df=new SimpleDateFormat(DATE_FORMAT);
        String thisdate = df.format(date.getTime() + diffDays * 24 * 60 * 60 * 1000l);
        return DateUtils.convert(thisdate + " " + DAYTIME_START);
    }
	/**
     * 返回两个时间的相差天数
     * @param startTime 对比的开始时间
     * @param endTime 对比的结束时间
     * @return 相差天数
     */
    
    public static Long getTimeDiff(String startTime, String endTime) {
		Long days = null;
		Date startDate=null;
		Date endDate=null;
		try {
			if(startTime.length()==10 && endTime.length()==10){
				 startDate = new SimpleDateFormat(DATE_FORMAT).parse(startTime);
				 endDate = new SimpleDateFormat(DATE_FORMAT).parse(endTime);
			}else{
				 startDate = new SimpleDateFormat(DATE_TIME_FORMAT).parse(startTime);
				 endDate = new SimpleDateFormat(DATE_TIME_FORMAT).parse(endTime);
			}
			
			Calendar c = Calendar.getInstance();
			c.setTime(startDate);
			long l_s = c.getTimeInMillis();
			c.setTime(endDate);
			long l_e = c.getTimeInMillis();
			days = (l_e - l_s) / 86400000;
		} catch (ParseException e) {
			logger.error("时间工具类异常:" ,e);;
			 if (logger.isWarnEnabled()) {
                 logger.warn(e.getMessage());
             }
			 days = null;
		}
		return days;
	}
	
	/**
     * 返回两个时间差（1小时10分钟）
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public static String getTimeDiffs(Date startTime, Date endTime) {
    	String res="";
    	
    	long t = endTime.getTime()-startTime.getTime();
    	long d = t/(24*60*60*1000);
    	long ds = t%(24*60*60*1000);
    	long h = ds/(60*60*1000);
    	long hs = ds%(60*60*1000);
    	long s = hs/(60*1000);
    	if(d>0){
    		res+=d+"天"+h+"小时"+s+"分钟";
    	}
    	else if(h>0){
    		res+=h+"小时"+s+"分钟";
    	}
    	else{
    		res+=s+"分钟";
    	}
    	return res;
    	
    }
	public static void main(String[] args) {
        Date date = new Date();
        System.out.println(DateUtils.getEndDatetime(date));
        System.out.println(DateUtils.getStartDatetime(date,-3));
        System.out.println(DateUtils.getEndDatetime(date,3));
        System.out.println(DateUtils.addDay(new Date(), 1));
        System.out.println(DateUtils.addDayNew(new Date(), Long.parseLong("-28")));
        System.out.println(DateUtils.addDay(new Date(),0));
    }
	
	/**
	 * 使用参数Format将字符串转为Date
	 */
	public static Date parse(String strDate, String pattern)
			throws ParseException {
		return StringUtils.isBlank(strDate) ? null : new SimpleDateFormat(
				pattern).parse(strDate);
	}

	/**
	 * 将传入的String类型的时�?YYYY-MM-dd)转换成date类型并返�?
	 * @return
	 */
	public static Date StringToDate(String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time = sdf.parse(date);
			return time;
		} catch (Exception e) {
			logger.error("时间工具类异常:" ,e);;
		}
		return null;
	}
    private DateUtils() {
    }
}
